import React from 'react';
import { Redirect, Switch, Route } from 'react-router-dom'//BrowserRouter模式，路径
import { useHistory } from 'react-router-dom';
import './App.css';
import { Tag } from 'antd';
import { Button } from 'antd';
import routers from './router/index';
import usePrevious from './hooks/usePrevious';
import Auth from './HOC/Auth';
import NeedAuth from './components/NeedAuth';

function App() {
  const history = useHistory();
  const [state, changeHistoryArr] = usePrevious();

  const goHome = () => {
    const data = { pathname: "/home", query: { id: '123', tagName: 'Home组件' } } as any
    history.push(data);
    changeHistoryArr(data, 'push');
  }
  const goLogin = () => {
    const data = { pathname: "/login", query: { id: '123', tagName: 'Login组件' } } as any
    history.push(data);
    changeHistoryArr(data, 'push');
  }
  const goInsurance = () => {
    const data = { pathname: "/insurance", query: { id: '123', tagName: 'Insurance组件' } } as any
    history.push(data);
    changeHistoryArr(data, 'push');
  }

  const onClose = (index: number) => {
    console.log('index', index);
    changeHistoryArr(index, 'delete');
  }
  return (
    <div className="App">
      <div>
        {
          Array.isArray(state?.historyArr) && state?.historyArr.map((item: any, index: number) => {
            return <Tag color="magenta" closable onClose={() => onClose(index)} key={Math.random()} >{item.query
              .tagName}</Tag>
          })
        }
      </div>
      <Button type="primary" onClick={goLogin}>跳转到Login组件</Button>
      <Button onClick={goInsurance}>跳转到Insurance组件</Button>
      <Button type="primary" danger onClick={goHome}>跳转到Home组件</Button>
      <Switch>
        <Auth path='/NeedAuth'><NeedAuth /></Auth>
        {
          routers.map((item) => {
            switch (item.path) {
              case '/':
                {
                  console.log('to', item.to);
                  //如果匹配的地址都没有的时候就重定向
                  return item.redirect && <Redirect key={item.key} to={item.to} exact={item.exact ? true : false} />
                }
              default: {
                return <Route key={item.key} path={item.path} component={item.component} exact={item.exact ? true : false} />
              }
            }
          })
        }
      </Switch>
    </div>
  );
}

export default App;
